<?php
/**
 * Created by PhpStorm.
 * User: CYJiao
 * Date: 6/8/15
 * Time: 09:50
 */


class PatientController extends Controller
{

    /**
     * Method returning filters array.
     */
    public function filters(){
        return array(
            'accessControl',//Performs access control for CRUD operations
        );
    }

    /**
     * Defines User Access Level.
     */
    public function accessRules(){
        return array(
            array('allow',
                'actions'=>array(),//Actions allowed
                'roles'=>array('@'),//Roles allowed to perform actions
            ),
            array('deny',
                'actions'=>array(),//Actions not allowed
                'roles'=>array('*'),//Roles not allowed to perform actions
            ),
        );
    }

    /**
     * Declares class-based actions.
     */
    public function actions(){
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'height'=>37,
                'minLength'=>4,
                'maxLength'=>6,
                'backColor'=>0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    }

    /**
     * Get ID from ID Server
     */
    private function getAutoID(){
        $id = curl_init();
        curl_setopt($id, CURLOPT_HEADER, 0);
        curl_setopt($id, CURLOPT_VERBOSE, 0);
        curl_setopt($id, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($id, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
        curl_setopt($id, CURLOPT_POST, true);
        curl_setopt($id, CURLOPT_URL, 'http://120.24.170.79:8080/push_call_server/get-id.do?accessToken=25da2c6fc3b8e5cfcd460b3367f7788e&logicid=8');
        $responseID = curl_exec($id);
        $result = json_decode($responseID,true);
        if($result['code']==0){
            return $result['content']['id'];
        }
    }

    private function register($phone,$password){
        $id = curl_init();
        curl_setopt($id, CURLOPT_HEADER, 0);
        curl_setopt($id, CURLOPT_VERBOSE, 0);
        curl_setopt($id, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($id, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
        curl_setopt($id, CURLOPT_URL, 'http://sso.o2omedical.com:8080/tys_sso_server/register.do?accessToken=25da2c6fc3b8e5cfcd460b3367f7788e&phone='.$phone.'&password='.$password.'&status=1&logicId=2');
        $responseID = curl_exec($id);
        $result = json_decode($responseID,true);
        return $result;
    }


    /******************************************************************************************
     * Functions in Accordion and Panel
     ******************************************************************************************/

    /**
     * Get Patient Main Accordion
     * @param bigint $pk_outpatient_id
     */
    public function actionGetPatientsMainAccordion($pk_outpatient_id){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->layout='main';
            $this->render('patientmainaccordion',array('pk_outpatient_id'=>$pk_outpatient_id));
        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

    /**
     * Get Patient Main Panel
     * @param bigint $pk_outpatient_id
     */
    public function actionPatientMainPanel($pk_outpatient_id){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->layout='main';
            $this->render('patientmainpanel',array('pk_outpatient_id'=>$pk_outpatient_id));
        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

    public function actionAdd(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            if(isset($_POST['true_name'])){



                $result = array();

                $count = Yii::app()->ssodb->createCommand("SELECT count(*) as count from tbl_sso_user where phone='{$_POST['phone']}'")->queryAll();
                if($count[0]['count'] > 0){
                    $result['status'] = 2;
                    echo json_encode($result);
                    exit;

                }
               
                $patient =new TblOutpatients();
                $d = date('Y-m-d H:i:s',time());
                $patient->pk_outpatient_id = $this->getAutoID();
                $patient->attributes = $_POST;
                $patient->create_time = $d;
                $patient->update_time = $d;
                $patient->username = time();
                $y = (date('Y',time()) - $_POST['age']);
                $patient->dob = $y.'-01-01 13:29:43';

                //用户注册流程
                if(!empty($_POST['sort_message']) && $_POST['sort_message'] == Yii::app()->session['meaasge']){
                    $password = rand(100000,999999);
                   //单点登录表
                   $register_ = $this->register($_POST['phone'],md5($password));
                   //插入用户表
                   $user = new TblUsers();
                   $user->pk_user_id = $this->getAutoID();
                   $user->phone = $_POST['phone'];
                   $user->user_type = 1;
                   $user->user_status = 1;
                   $user->create_time = $d;
                   $user->update_time = $d;
                   $user->save(false);

                   //插入用户信息表
                   $user_information = new TblUserInformation();
                   $user_information->pk_fk_user_id = $user->pk_user_id;
                   $user_information->true_name = $_POST['true_name'];
                   $user_information->gender = $_POST['gender'];
                   $user_information->age = $_POST['age'];
                   $user_information->blood_type = $_POST['blood_type'];
                   $user_information->weight = $_POST['weight'];
                   $user_information->stature = $_POST['stature'];
                   $user_information->create_time = $d;
                   $user_information->update_time = $d;
                   $user_information->save(false);

                   $user_has_outpatient = new TblUsersHasTblOutpatients();
                   $user_has_outpatient->fk_user_id = $user->pk_user_id;
                   $user_has_outpatient->fk_outpatient_id = $patient->pk_outpatient_id;
                   $user_has_outpatient->key_user = 1;
                   $user_has_outpatient->connected = 1;
                   $user_has_outpatient->relationship = 1;
                   $user_has_outpatient->create_time = $d;
                   $user_has_outpatient->update_time = $d;
                   $user_has_outpatient->save(false);

                }

                //Yii::app()->ssodb->createCommand($sql)->queryAll();
                
                if($patient->save()){

                    $outpatient_locations = new TblOutpatientLocations();
                    $outpatient_locations->pk_fk_outpatient_id = $patient->pk_outpatient_id;
                    $outpatient_locations->create_time = $d;
                    $outpatient_locations->update_time = $d;
                    $outpatient_locations->save(false);


                     //Action logging
                    // $log = new Log600100(); //Create new empty record
                    // $log->action = 'save_patient';//Saving the action type
                    // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                    // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                    // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                    // $log->target = $patient->pk_outpatient_id;//针对对象
                    // $log->save(false);//Saving the entire record with validation


                    $doctors_to_Outpatients = new TblDoctorsHasTblOutpatients();
                    $doctors_to_Outpatients->fk_doctor_id = Yii::app()->session['id'];
                    $doctors_to_Outpatients->fk_outpatient_id = $patient->pk_outpatient_id;
                    $doctors_to_Outpatients->disease_type = 1;
                    $doctors_to_Outpatients->key_doctor = 1;
                    $doctors_to_Outpatients->connected = 1;
                    $doctors_to_Outpatients->create_time = $d;
                    $doctors_to_Outpatients->update_time = $d;
                    $doctors_to_Outpatients->save(false);

                    // $log = new Log600100(); //Create new empty record
                    // $log->action = 'connect_patient';//Saving the action type
                    // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                    // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                    // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                    // $log->target = $patient->pk_outpatient_id;//针对对象
                    // $log->save(false);//Saving the entire record with validation

                    //postSMS('欢迎下载在线医生www.o2omedical.com/p.html，如需帮助请致电4009600939',$_POST['phone']);

                    $result['status'] = 0;
                    $result['patient_id'] = $patient->pk_outpatient_id;
                    $result['true_name'] = $_POST['true_name'];
                    $result['username'] = $patient->username;
                }else{
                    $result['status'] = 1;
                    $result['result'] = json_encode($patient->getErrors());
                }

                send_sms_yun('9a9c498403674eb2c191be72d7140d0d', '902351', '#phone#='.$_POST['phone'].'&#password#='.$password,$_POST['phone']);

                postSMS($_POST['phone'],'欢迎下载在线医生www.o2omedical.com/p.html，如需帮助请致电4009600939');

                echo json_encode($result);

            }else{
                $this->layout='main';
                $this->render('add');
            }
            
        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

    public function actionSend_message(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {

            $count = Yii::app()->ssodb->createCommand("SELECT count(*) as count from tbl_sso_user where phone='{$_POST['phone']}'")->queryAll();
            if($count[0]['count'] > 0){
                echo '1';
            }else{
                $mobile = $_POST['phone'];
                Yii::app()->session['meaasge'] = rand(1000,9999);

                send_sms_yun('9a9c498403674eb2c191be72d7140d0d', '890053', '#code#='.Yii::app()->session['meaasge'], $mobile);
                echo Yii::app()->session['meaasge'];
            }


        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

    /******************************************************************************************
     * Functions in Patient Information
     ******************************************************************************************/

    /**
     * Get Patient Information
     * @param bigint $pk_outpatient_id
     */
    public function actionGetPatientInformation($pk_outpatient_id){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $patientInformation = TblOutpatients::model()->findByAttributes(array('pk_outpatient_id'=>$pk_outpatient_id));

            //Action logging
            // $log = new Log600100(); //Create new empty record
            // $log->action = 'list_patient';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = $pk_outpatient_id;//针对对象
            // $log->save(false);//Saving the entire record with validation


            $this->layout='main';
            $this->render('patientinformation',array('pk_outpatient_id'=>$pk_outpatient_id,'patientInformation'=>$patientInformation));
        }
        else
            $this->redirect(array('site/login'));//View redirection
    }

	
	    /**
     * Get Patient Information
     * @param bigint $pk_outpatient_id
     */
    public function actionSavePatientInformation($pk_outpatient_id){
        $result = array('status'=>0,'result'=>0);
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $patient = TblOutpatients::model();
			$data = $_POST;
			$d = date('Y-m-d h:i:s');
			$data['update_time'] = $d;
            if(!$patient->updateByPk($pk_outpatient_id,$data)){
                $result['status'] = 1;
                $result['result'] = json_encode($patient->getErrors());
            }else{
                //Action logging
                // $log = new Log600100(); //Create new empty record
                // $log->action = 'save_patient';//Saving the action type
                // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                // $log->target = $pk_outpatient_id;//针对对象
                // $log->save(false);//Saving the entire record with validation


            }
        }
        else
            $result = array('status'=>2,'result'=>0);
        echo json_encode($result);
    }
}
